#!/usr/bin/env bash

# Helper script for running commands in a golang build/runtime environment for testing/vendoring/building a go module

set -e -o pipefail

usage() {
   cat >&2 <<EOF
$(basename "${0}")
                --module-path <path to Go module>
                --go-version <go version>
                --go-mod-cache <path to set up the go mod cache>
                --command "<command to run>"
Runs

Required:
    --module-path               The path of the Go module to mount into the container
    --sdk-image                 Name of the SDK image to use
    --go-mod-cache              The Go module cache path to mount into the container
    --command                   The command to run in the SDK container
EOF
}

required_arg() {
   local arg="${1:?}"
   local value="${2}"
   if [ -z "${value}" ]; then
      echo "ERROR: ${arg} is required" >&2
      exit 2
   fi
}

parse_args() {
  while [ ${#} -gt 0 ] ; do
    case "${1}" in
        --help ) usage; exit 0 ;;
        --module-path ) shift; GO_MODULE_PATH="${1}" ;;
        --sdk-image ) shift; SDK_IMAGE="${1}" ;;
        --go-mod-cache ) shift; GO_MOD_CACHE="${1}" ;;
        --command ) shift; COMMAND="${@:1}" ;;
        *) ;;
    esac
    shift
  done

  # Required arguments
  required_arg "--module-path" "${GO_MODULE_PATH}"
  required_arg "--sdk-image" "${SDK_IMAGE}"
  required_arg "--go-mod-cache" "${GO_MOD_CACHE}"
  required_arg "--command" "${COMMAND}"
}

DOCKER_RUN_ARGS="--network=host"

parse_args "${@}"

# Pass through relevant Go variables, from the config or environment.
go_env=( )
for i in GOPROXY GONOPROXY GOPRIVATE ; do
  if command -v go >/dev/null 2>&1 ; then
    govar="$(go env ${i})"
    if [ -n "${govar}" ] ; then
      go_env[${#go_env[@]}]="--env=${i}=${govar}"
    fi
  elif [ -n "${!i}" ] ; then
    go_env[${#go_env[@]}]="--env=${i}=${!i}"
  fi
done

# Go accepts both lower and uppercase proxy variables, pass both through.
proxy_env=( )
for i in http_proxy https_proxy no_proxy HTTP_PROXY HTTPS_PROXY NO_PROXY ; do
  if [ -n "${!i}" ]; then
    proxy_env[${#proxy_env[@]}]="--env=$i=${!i}"
  fi
done

docker run --rm \
  -e GOCACHE='/tmp/.cache' \
  -e GOPATH='/tmp/go' \
  "${go_env[@]}" \
  "${proxy_env[@]}" \
  --user "$(id -u):$(id -g)" \
  --security-opt label:disable \
  ${DOCKER_RUN_ARGS} \
  -v "${GO_MOD_CACHE}":/tmp/go/pkg/mod \
  -v "${GO_MODULE_PATH}":/usr/src/host-ctr \
  -w /usr/src/host-ctr \
  "${SDK_IMAGE}" \
    bash -c "${COMMAND}"
